package com.itheima.homework15;

import java.io.IOException;
import java.net.*;
import java.text.SimpleDateFormat;
import java.util.Date;

public class Test03 {
    public static void main(String[] args) throws InterruptedException, SocketException, UnknownHostException {
        /*
        请编写程序，分别模拟使用UDP协议发送和接收数据的两个设备，
        发送端数据将当前系统时间转换为字符串，发送给接收端，每秒发送一次。
        接收端接收到数据，
        将数据以及数据的来源打印到控制台。要求发送数据和接收数据分别开启线程实现。
         */
        DatagramSocket socket=new DatagramSocket();

      new Thread(()->{


          while (true){//因为要一直发送，定义死循环
              Date date=new Date();

              SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
              String format = sdf.format(date);

              byte[] bytes = format.getBytes();
              InetAddress byName = null;
              try {
                  byName = InetAddress.getByName("192.168.13.24");
              } catch (UnknownHostException e) {
                  e.printStackTrace();
              }
              DatagramPacket packet=new DatagramPacket(bytes,bytes.length,byName,10086);
              try {

                  socket.send(packet);
                  Thread.sleep(1000);
              } catch (IOException e) {
                  e.printStackTrace();
              } catch (InterruptedException e) {
                  e.printStackTrace();
              }
          }


      }).start();



        DatagramSocket ds=new DatagramSocket(10086);
        new Thread(()->{//因为要一直接收，定义死循环
            while (true){


            byte [] bytes=new byte[1024];
            DatagramPacket dp=new DatagramPacket(bytes,0,bytes.length);
            try {
                ds.receive(dp);
                InetAddress address = InetAddress.getByName("192.168.13.24");
                System.out.println(address.getHostAddress()+"发送数据"+new String(bytes,0,bytes.length));
            } catch (IOException e) {
                e.printStackTrace();
            }

        }}
        ).start();


    }


}
